﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace Pay.Data {
	public static class DbSetExtend {
		public static bool Exist<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> queryWhere) where TEntity : class {
			return (dbSet.Count<TEntity>(queryWhere) > 0);
		}

		public static IQueryable<TEntity> FindBy<TEntity, TKey>(this DbSet<TEntity> dbSet, int pageNumber, int pageSize, out int total, Expression<Func<TEntity, TKey>> orderBy, bool isAsc = true) where TEntity : class {
			total = dbSet.Count<TEntity>();
			IQueryable<TEntity> source = from item in dbSet
										 where true
										 select item;
			if (isAsc) {
				source = source.OrderBy(orderBy);
			} else {
				source = source.OrderByDescending(orderBy);
			}
			return source.Skip(((pageNumber - 1) * pageSize)).Take(pageSize);
		}

		public static IQueryable<TEntity> FindBy<TEntity, TKey>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> queryWhere, int pageNumber, int pageSize, out int total, Expression<Func<TEntity, TKey>> orderBy, bool isAsc = true) where TEntity : class {
			total = dbSet.Count(queryWhere);
			if (isAsc) {
				return dbSet.Where(queryWhere).OrderBy(orderBy).Skip((pageNumber - 1) * pageSize).Take(pageSize);
			}
			return dbSet.Where(queryWhere).OrderByDescending(orderBy).Skip((pageNumber - 1) * pageSize).Take(pageSize);
		}

		public static IQueryable<TEntity> FindBy<TEntity, TKey>(this IQueryable<TEntity> entities, Expression<Func<TEntity, bool>> where, int pageNumber, int pageSize, out int total, Expression<Func<TEntity, TKey>> orderBy, bool isAsc = true) {
			total = entities.Count(where);
			if (isAsc) {
				return entities.Where(where).OrderBy(orderBy).Skip((pageNumber - 1) * pageSize).Take(pageSize);
			}
			return entities.Where(where).OrderByDescending(orderBy).Skip((pageNumber - 1) * pageSize).Take(pageSize);
		}

		public static TEntity FindById<TEntity>(this DbSet<TEntity> dbSet, object id) where TEntity : class {
			return dbSet.Find(new object[] { id });
		}

		public static void Remove<TEntity>(this DbSet<TEntity> dbSet, params object[] ids) where TEntity : class {
			List<TEntity> entities = new List<TEntity>();
			foreach (object obj2 in ids) {
				entities.Add(dbSet.FindById(obj2));
			}
			dbSet.RemoveRange(entities);
		}

		public static void Remove<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> where) where TEntity : class {
			IEnumerable<TEntity> entities = dbSet.Where(where);
			dbSet.RemoveRange(entities);
		}
	}
}

